extends IBasicComponent


class_name EventListener


## 需要监听的事件列表,为空则不进行过滤
@export var listen_events: Array[CharacterUnit.Event] = []
## 需要监听的行为列表,为空则不进行过滤
@export var listen_effects: Array[CharacterUnit.Effect] = []
## 需要监听的对象
@export var character: CharacterComponent = null


@export_category("Debug")
@export var is_debug: bool = false
@export_category("")


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "character": IComponent.find_up.bind(self, func(x): return x is CharacterComponent, character),
    }, super.__check_exports())

func __init_hooks() -> Dictionary:
    return IComponent.merge({
        character.event_on_message: __on_listen_message,
        character.event_on_effect: __on_listen_effect,
    }, super.__init_hooks())

# 过滤消息
func __on_listen_message(c: CharacterComponent, e: CharacterEvent) -> void:
    if listen_events.size() < 1 or listen_events.has(e.type):
        if is_debug:
            var n: String = character.wrapper.name if character.wrapper else character.name
            print("%s[%s] %s on_message:%s %s" % [n, character, self, CharacterUnit.EventDesc[e.type], e.meta])
        on_message(e)

# 过滤行为
func __on_listen_effect(c: CharacterComponent, type: CharacterUnit.Effect, e: CharacterEvent) -> void:
    if listen_effects.size() < 1 or listen_effects.has(type):
        if is_debug:
            var n: String = character.wrapper.name if character.wrapper else character.name
            print("%s[%s] %s on_effect:%s => %s %s" % [n, character, self, CharacterUnit.EventDesc[e.type], CharacterUnit.EffectDesc[type], e.meta])
        on_effect(type, e)

# 处理消息
func on_message(e: CharacterEvent) -> void:
    pass

# 处理行为
func on_effect(type: CharacterUnit.Effect, e: CharacterEvent) -> void:
    pass
